package com.sgb.kjwl.view.ui.activity.manage;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.im.immodel.IMUtils;
import com.sgb.capital.view.ui.activity.BusinessManagementActivity;
import com.sgb.goods.entity.GoodsItemEntity;
import com.sgb.goods.view.activity.inquiry.NewPurchasesActivity;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtWebsiteInfoBinding;
import com.sgb.kjwl.databinding.ItemWebsiteBottomBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.manage.AnnouncementListEntity;
import com.sgb.kjwl.model.entity.manage.WebsiteBannerEntity;
import com.sgb.kjwl.model.entity.manage.WebsiteConfigureEntity;
import com.sgb.kjwl.model.entity.manage.WebsiteInfoEntity;
import com.sgb.kjwl.model.entity.manage.WebsiteMemberEntity;
import com.sgb.kjwl.model.entity.self.PermissionMenuEntity;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.ScanActivity;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.self.SelfQrCodeActivity;
import com.sgb.kjwl.view.ui.activity.self.SuggestionFeedbackActivity;
import com.sgb.kjwl.view.ui.activity.self.company.AgentCentralizedMiningActivity;
import com.sgb.kjwl.view.ui.activity.self.company.AgentEnquiryActivity;
import com.sgb.kjwl.view.ui.activity.self.mine.PersonOrderActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.GetPositionActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.manage.TabFirstAdapter;
import com.sgb.kjwl.view.ui.adapter.manage.TagAdapter;
import com.sgb.kjwl.view.ui.fragment.manage.BusinessDynamicsForWebsite;
import com.sgb.kjwl.view.ui.fragment.manage.DemandAnnouncementForWebsite;
import com.sgb.kjwl.view.ui.fragment.manage.HonorGloryForWebsite;
import com.sgb.kjwl.view.ui.fragment.manage.IntellectualPropertyForWebsite;
import com.sgb.kjwl.view.ui.fragment.manage.IntroductionForWebsite;
import com.sgb.kjwl.view.ui.fragment.manage.OperatingBusinessForWebsite;
import com.sgb.kjwl.view.ui.fragment.manage.OperatingResultsForWebsite;
import com.sgb.kjwl.view.ui.fragment.manage.OtherInquiryFragment;
import com.sgb.kjwl.view.ui.fragment.manage.PromotionalAlbumForWebsite;
import com.sgb.kjwl.view.ui.fragment.manage.SpecialAssetsForWebsite;
import com.sgb.kjwl.view.ui.fragment.manage.SpecialQualificationForWebsite;
import com.sgb.kjwl.view.widget.AddPopWindow;
import com.sgb.kjwl.view.widget.PickHallBidingPopWindow;
import com.sgb.kjwl.view.widget.manage.ChooseTypeFragment;
import com.sgb.kjwl.view.widget.manage.WebsiteHeadView;
import com.sgb.kjwl.view.widget.manage.WebsiteUtils;
import com.sgb.kjwl.view.widget.self.MenuClickUtils;
import com.sgb.kjwl.view.widget.self.permission.UserPermissionUtils;
import com.sgb.kjwl.viewmodel.manage.WebsiteInfoModel;
import com.sgb.link.entity.PickFilterEntity;
import com.sgb.link.utils.SizeUtils;
import com.sgb.member.MemberConfig;
import com.sgb.member.entity.MemberBean;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.ui.activity.MemberApplyJoinActivity;
import com.sgb.member.ui.activity.MemberInviteJoinActivity;
import com.sgb.member.ui.activity.MemberPriceActivity;
import com.sgb.member.ui.activity.MemberTransferActivity;
import com.stx.xhb.androidx.XBanner;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.ACAdminDialogUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.LiuHaiPingUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.AppBarStateChangeListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Author LiWei
 * Create Time 2021/4/14
 * Description 企业网站
 */
@Route(path = AppRouteConstant.WEBSITEINFO_URL)
public class WebsiteInfoActivity extends AppActivity implements com.sgb.kjwl.view.widget.manage.ChooseTypeFragment.ClickItemCallBack {

    @Inject
    WebsiteInfoModel viewModel;
    private AtWebsiteInfoBinding binding;

    public static final int WEBSITE_FOR_COMPANY = 1;//企业网站
    public static final int WEBSITE_FOR_TEAM = 2;//团队网站
    public static final int WEBSITE_FOR_PERSONAL = 0; //个人网站
    public static final int WEBSITE_FOR_ORGANIZE = 3;//组织网站

    public static final String TYPE_IS_MYSELF = "type_is_myself"; //个人网站

    private String websiteNo;//企业no或个人userNo
    private int websiteType;
    private RequestManager requestManager;
    private int currentPosition = 0;
    private int childPosition = 0;
    private PickHallBidingPopWindow mPopup;
    private WebsiteInfoEntity entity;
    private boolean isMyself;

    private TagAdapter mAdapter;

    //自营
    private View mSelfSupportHeaderView;
    //会员等级
    private View mMemberHeaderView;
    //信用评分
    private View mScoreView;
    private TextView tvScore;

    private TextView mMemberTv;

    private BottomAdapter mBottomAdapter;

    private TabFirstAdapter mTabAdapter;

    private List<PermissionMenuEntity.ListEntity> totalMenu = new ArrayList<>();

    private BottomSheetBehavior<LinearLayout> bottomSheetBehavior;

    //订单的权限
    private ArrayList<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> mMenus = new ArrayList<>();

    //申请的权限
    private ArrayList<PickFilterEntity<Object>> mApplyMenus = new ArrayList<>();

    //代办集采
    private List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> mAgentCentralizedMiningMenus = new ArrayList<>();

    private ArrayList<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> mReallyAgentCentralizedMiningMenus = new ArrayList<>();

    //是否有权限进入付款页面
    private boolean goToPayEnable = false;

    //是否有询价商品的权限
    private boolean permissionEnquiryShop = false;

    public boolean isEnableClick = false;//是否可以点击

    private AddPopWindow addPopWindow;

    private ActivityResultLauncher<Intent> launchForesult;


    private WebsiteMemberEntity mMemberEntity;

    private WebsiteConfigureEntity mConfigureEntity;

    private List<Integer> mFilterMenus = new ArrayList<>();

    //ViewStub 相关布局
    private ViewStub vsWebsite;
    private RecyclerView tabFirstRecyclerView;
    private ViewPager viewPager;
    private LinearLayout linLl, llMore;
    private ImageView ivCommonView, ivMore;
    private View grayLayout;
    private View linView;
    private Space mBottomSpace;
    private View mEmptyView;
    private HorizontalScrollView horizontalScrollView;

    private List<AnnouncementListEntity> mAnnouncementList = new ArrayList<>();//公告列表
    private boolean isGetData = false; //是否可以获取到公告列表数据
    private boolean isPermission = false;//邀请或申请权限
    @Autowired(name = "No")
    public String No;
    @Autowired(name = "Type")
    public int Type;
    //是否是从外部跳转过来的
    @Autowired(name = "isARouter")
    public boolean isARouter;

    /**
     * 企业网站  团队网站  个人网站
     *
     * @param context
     * @param websiteNo   企业no或个人userNo
     * @param websiteType 1 企业网站 2 团队网站  0 个人网站
     */
    public static void start(Context context, String websiteNo, int websiteType) {
        Intent intent = new Intent();
        intent.putExtra("websiteNo", websiteNo);
        intent.putExtra("websiteType", websiteType);
        intent.setClass(context, WebsiteInfoActivity.class);
        context.startActivity(intent);
    }

    /**
     * 企业网站  团队网站  个人网站
     *
     * @param context
     * @param websiteNo
     * @param websiteType 1 企业网站 2 团队网站  3 个人网站
     * @param isMyself    是不是自己
     */
    public static void start(Context context, String websiteNo, int websiteType, boolean isMyself) {
        Intent intent = new Intent();
        intent.putExtra("websiteNo", websiteNo);
        intent.putExtra("websiteType", websiteType);
        intent.putExtra(TYPE_IS_MYSELF, isMyself);
        intent.setClass(context, WebsiteInfoActivity.class);
        context.startActivity(intent);
    }

    /**
     * 根据传入的参数定位切换到一级和二级指定tab上
     *
     * @param context
     * @param websiteNo       企业no或个人userNo
     * @param websiteType     网站类型
     * @param currentPosition 第一级tab下标
     * @param childPosition   第二级tab下标
     */
    public static void start(Context context, String websiteNo, int websiteType, int currentPosition, int childPosition) {
        Intent intent = new Intent();
        intent.putExtra("websiteNo", websiteNo);
        intent.putExtra("websiteType", websiteType);
        intent.putExtra("currentPosition", currentPosition);
        intent.putExtra("childPosition", childPosition);
        intent.setClass(context, WebsiteInfoActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent).
                enterpriseManageModule(new EnterpriseManageModule(this)).
                build().inject(this);
    }

    @SuppressLint({"AutoDispose", "CheckResult"})
    @Override
    protected void initView() {
        //判断EvEntBus是否存在
        if (!EventBus.getDefault().isRegistered(this)) {
            //注册EvEntBus
            EventBus.getDefault().register(this);
        }
        requestManager = Glide.with(this);
        if (isARouter) {
            websiteNo = No;
            websiteType = Type;
        } else {
            websiteNo = getIntent().getStringExtra("websiteNo");
            websiteType = getIntent().getIntExtra("websiteType", WEBSITE_FOR_COMPANY);
            currentPosition = getIntent().getIntExtra("currentPosition", 0);//当前tab显示位置
            childPosition = getIntent().getIntExtra("childPosition", 0);//第二层tab显示位置
        }
        isMyself = getIntent().getBooleanExtra(TYPE_IS_MYSELF, false);
        binding = DataBindingUtil.setContentView(WebsiteInfoActivity.this, R.layout.at_website_info);
        binding.setViewModel(viewModel);
        binding.include.ivBack.setOnClickListener(this);
        binding.include.rightImageView.setImageResource(R.drawable.btn_more_white);
        binding.include.rightImageView.setOnClickListener(this);
        binding.linIm.setOnClickListener(this);
        binding.linAttention.setOnClickListener(this);
        binding.linInquiry.setOnClickListener(this);
        binding.linJoin.setOnClickListener(this);
        binding.linInvite.setOnClickListener(this);
        binding.ivAddressLat.setOnClickListener(this);
        binding.ivAddressLatPerson.setOnClickListener(this);
        binding.tvAttention.setOnClickListener(this);
        binding.tvVR.setOnClickListener(this);
        binding.tvAnnouncementMore.setOnClickListener(this);
        binding.websiteHeadView.setCallBack(new WebsiteHeadView.ClickHeadView() {
            @Override
            public void clickVr(@NotNull String vrUrl) {
                WebViewX5HostActivity.start(WebsiteInfoActivity.this, entity.getVrUrl());
            }

            @Override
            public void clickAttention() {
                attention();
            }

            @Override
            public void clickVideo(@NotNull WebsiteInfoEntity entity) {
                WebsiteUtils.getInstance().openVideo(WebsiteInfoActivity.this, entity.getVideo(), entity.getVideoUrl(), entity.getCoverUrl());
            }

            @Override
            public void clickMap(@NotNull WebsiteInfoEntity entity) {
                openMap(entity);
            }
        });
        initBottomRecyclerView();
        initBottomSheetBehavior();
        //initEmptyRecycleView();
        initAddPopView();

        //开启tab布局加载
        Observable.timer(200, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    initTabRecycleView();
                });

        binding.bgLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (bottomSheetBehavior != null && bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
                return true;
            }
        });
        initLiveData();
        mTabAdapter = new TabFirstAdapter(this, R.layout.item_website_tab_first);
        binding.appBar.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (!isGetData) {
                    return;
                }
                if (state == State.EXPANDED) {
                    //展开状态
                    if (mAnnouncementList.size() > 1) {
                        binding.viewFlipper.startFlipping();
                    } else {
                        binding.viewFlipper.stopFlipping();
                    }
                } else if (state == State.COLLAPSED) {
                    //折叠状态
                    binding.viewFlipper.stopFlipping();
                } else {
                    binding.viewFlipper.stopFlipping();
                }
            }
        });


        ViewGroup.LayoutParams layoutParams = binding.include.liuhaiStatusView.getLayoutParams();
        layoutParams.height = LiuHaiPingUtils.getStatusBarHeight(this);
        binding.include.liuhaiStatusView.setLayoutParams(layoutParams);

        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) binding.flHead.getLayoutParams();
        lp.topMargin = LiuHaiPingUtils.getStatusBarHeight(this) + SizeUtils.dp2px(48);
        binding.flHead.setLayoutParams(lp);
        isGetData = false;
    }

    //初始化addPopWindow
    private void initAddPopView() {
        addPopWindow = new AddPopWindow(getActivity());
        addPopWindow.setOnClickCallBack(new AddPopWindow.OnClickCallBack() {
            @Override
            public void scan() {
                //获取相机权限
                checkPermission();
            }

            @Override
            public void addFriend() {
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    //   MToast.showToast(this, "您还没有登录，请先登录");
                    VerificationCodeLoginActivity.start(getActivity(), false);
                } else {
                    MToast.showToast(WebsiteInfoActivity.this, "功能暂未开放");
                }
            }

            @Override
            public void groupChat() {
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    //   MToast.showToast(this, "您还没有登录，请先登录");
                    VerificationCodeLoginActivity.start(getActivity(), false);
                } else {
                    MToast.showToast(WebsiteInfoActivity.this, "功能暂未开放交流");
                }
            }

            @Override
            public void qrCode() {
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    //   MToast.showToast(this, "您还没有登录，请先登录");
                    VerificationCodeLoginActivity.start(getActivity(), false);
                } else {
                    SelfQrCodeActivity.start(getActivity());
                }
            }

            @Override
            public void feedback() {
                SuggestionFeedbackActivity.start(getActivity());
            }

        });
        launchForesult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getData() == null) {
                    return;
                }
//                String s = result.getData().getStringExtra(OrganizationalStructureActivity.PEOPLE);
//                LogUtils.d("ChatFragment " +
//                        "=" + s);
//                if (TextUtils.isEmpty(s)) {
//                    return;
//                }
//                List<SelectGroupMemberEntity> data = new Gson().fromJson(s, new TypeToken<List<SelectGroupMemberEntity>>() {
//                }.getType());
//
//                talkingListViewModel.publishImMember(data);
            }
        });
    }

    //初始化空的recycleView 主要加头部信用评分和自营
    private void initEmptyRecycleView() {
        mAdapter = new TagAdapter(this, R.layout.item_tag_website_info, new ArrayList<>());
        //mAdapter.addHeaderView(getMemberView());//暂时隐藏会员等级文案
        if (websiteType == WEBSITE_FOR_COMPANY) {
            mAdapter.addHeaderView(getScoreView());
            mAdapter.addHeaderView(getSelfSupportView());
        }
        binding.recyclerViewEmpty.setAdapter(mAdapter);
    }


    private void initLiveData() {
        //网站底部区域审核权限
        viewModel.mCheckMenusLiveData.observe(this, new Observer<List<PickFilterEntity<Object>>>() {
            @Override
            public void onChanged(List<PickFilterEntity<Object>> pickFilterEntities) {
                isEnableClick = true;
                mApplyMenus.clear();
                mApplyMenus.addAll(pickFilterEntities);
            }
        });
        //网站底部区域付款权限
        viewModel.mPayMenusLiveData.observe(this, new Observer<List<PickFilterEntity<Object>>>() {
            @Override
            public void onChanged(List<PickFilterEntity<Object>> pickFilterEntities) {
                isEnableClick = true;
                goToPayEnable = pickFilterEntities != null && !pickFilterEntities.isEmpty();
            }
        });
        //网站底部区域订单权限
        viewModel.mMenusLiveData.observe(this, new Observer<List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>>>() {
            @Override
            public void onChanged(List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> pickFilterEntities) {
                isEnableClick = true;
                mMenus.clear();
                mMenus.addAll(pickFilterEntities);
            }
        });
        //网站底部集采
        viewModel.mCentralizedMiningLiveData.observe(this, new Observer<List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>>>() {
            @Override
            public void onChanged(List<PickFilterEntity<ArrayList<PickFilterEntity<Object>>>> pickFilterEntities) {
                isEnableClick = true;
                mAgentCentralizedMiningMenus.clear();
                mAgentCentralizedMiningMenus.addAll(pickFilterEntities);
            }
        });
        //网站底部询价
        viewModel.mEnquiryShopLiveData.observe(this, new Observer<List<PickFilterEntity<Object>>>() {
            @Override
            public void onChanged(List<PickFilterEntity<Object>> pickFilterEntities) {
                isEnableClick = true;
                permissionEnquiryShop = pickFilterEntities != null && !pickFilterEntities.isEmpty();
            }
        });
        //网站广告页
        viewModel.webSiteBanners.observe(this, websiteBannerEntities -> {
            //setHeaderBanners(websiteBannerEntities);
            binding.websiteHeadView.setHeaderBanners(websiteBannerEntities, websiteType, requestManager);
        });
        //会员关系
        viewModel.websiteMember.observe(this, websiteMemberEntity -> {
            if (websiteMemberEntity.getDemand() && websiteMemberEntity.getSupply()) {//如果即是供方会员也是需方会员脏数据
                websiteMemberEntity.setDemand(false);
                websiteMemberEntity.setSupply(false);
            }
            mMemberEntity = websiteMemberEntity;
            binding.websiteHeadView.renderView(entity, requestManager, mMemberEntity);
            viewModel.getCompanyBottomMenus(websiteType, isMyself, websiteMemberEntity, mConfigureEntity);
        });
        //网站配置
        viewModel.mWebsiteConfigureEntity.observe(this, websiteConfigureEntity -> {
            //网站配置
            viewModel.getWebsiteInfo(websiteNo, websiteType);
            viewModel.getJudgeFirstMenuData(websiteNo, websiteType);
            mConfigureEntity = websiteConfigureEntity;
            renderView(websiteConfigureEntity);
        });
        //一级菜单过滤
        viewModel.mJudgeFirstMenus.observe(this, new Observer<List<Integer>>() {
            @Override
            public void onChanged(List<Integer> integers) {
                mFilterMenus.clear();
                if (integers != null) {
                    mFilterMenus.addAll(integers);
                    initTabLayout(mConfigureEntity == null ? null : mConfigureEntity.getNavigateBar(), integers);
                }
            }
        });
        //交流
        viewModel.mImMsg.observe(this, new Observer<LoginEntity>() {
            @Override
            public void onChanged(LoginEntity loginEntity) {
                if (loginEntity != null) {
                    if (TextUtils.isEmpty(loginEntity.getImAccount())) {
                        Toast.makeText(WebsiteInfoActivity.this, "im账号不能为空！！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    IMUtils.getInstance().buildSingleTalking(loginEntity.getImAccount());
                }
            }
        });
        //公告列表
        viewModel.mAnnouncementList.observe(this, new Observer<List<AnnouncementListEntity>>() {
            @Override
            public void onChanged(List<AnnouncementListEntity> announcementListEntities) {
                binding.llAnnouncement.setVisibility(View.VISIBLE);
                if (announcementListEntities != null) {
                    mAnnouncementList.addAll(announcementListEntities);
                }
                if (mAnnouncementList.isEmpty()) {
                    binding.llAnnouncement.setVisibility(View.GONE);
                    AnnouncementListEntity entity = new AnnouncementListEntity();
                    entity.setTitle("暂无公告");
                    mAnnouncementList.add(entity);
                }
                renderAnnouncementArea();
                isGetData = true;
            }
        });
    }

    private void renderAnnouncementArea() {
        if (mAnnouncementList.isEmpty()) return;
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        for (AnnouncementListEntity entity : mAnnouncementList) {
            TextView tv = new TextView(this);
            tv.setLayoutParams(lp);
            tv.setText(TextUtils.isEmpty(entity.getTypeName()) ? entity.getTitle() : entity.getTypeName() + ":" + entity.getTitle());
            tv.setGravity(Gravity.CENTER_VERTICAL);
            tv.setTextSize(12);
            tv.setTextColor(getResources().getColor(R.color.color_tab_one));
            tv.setSingleLine();
            tv.setEllipsize(TextUtils.TruncateAt.END);
            tv.setOnClickListener(v -> {
                if (!TextUtils.isEmpty(entity.getNo())) {
                    viewModel.getH5Url(this, entity.getNo(), "announcementDetail");
                }
            });
            binding.viewFlipper.addView(tv);
        }
        if (mAnnouncementList.size() == 1 && TextUtils.isEmpty(mAnnouncementList.get(0).getNo())) {
            binding.viewFlipper.stopFlipping();
        } else {
            binding.viewFlipper.startFlipping();
        }

    }

    //网站配置
    private void renderView(WebsiteConfigureEntity websiteConfigureEntity) {
        WebsiteConfigureEntity.ColorEntity colorEntity = websiteConfigureEntity.getColorScheme();
        binding.websiteHeadView.loadTemplate(websiteConfigureEntity.getUseTemplate(), websiteType);
        binding.websiteHeadView.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.websiteHeadView.setHeaderBanners(websiteConfigureEntity.getAdSettings(), websiteType, requestManager);
            }
        }, 200); //200ms后获取tab 防止 懒加载布局未加载数据已经获取
        if (colorEntity != null && !TextUtils.isEmpty(colorEntity.getColor())) {
            binding.include.topLayout.setBackgroundColor(Color.parseColor(colorEntity.getColor()));
            //String[] split = colorEntity.getBackgroundColor().split(",");
            //int argb = Color.argb((int) (Double.parseDouble(split[3].trim()) * 255), Integer.parseInt(split[0].trim()), Integer.parseInt(split[1].trim()), Integer.parseInt(split[2].trim()));
            //mTabAdapter.setTabColor(argb);
            mTabAdapter.setTabColor(Color.parseColor(colorEntity.getColor()));
        }
    }


    private void setHeaderBanners(List<WebsiteBannerEntity> bannerEntities) {
        if (bannerEntities.isEmpty()) {
            bannerEntities.add(new WebsiteBannerEntity());
        }
        binding.bannerWebsite.setBannerData(bannerEntities);
        binding.bannerWebsite.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                int errorImg = R.drawable.pic_default_bg;
                if (websiteType == WEBSITE_FOR_COMPANY || websiteType == WEBSITE_FOR_ORGANIZE) {
                    errorImg = R.drawable.img_website_banner_company_default;
                } else if (websiteType == WEBSITE_FOR_PERSONAL) {
                    errorImg = R.drawable.img_website_banner_person_default;
                } else if (websiteType == WEBSITE_FOR_TEAM) {
                    errorImg = R.drawable.img_website_banner_team_default;
                }
                requestManager.load(bannerEntities.get(position).getXBannerUrl()).placeholder(R.drawable.pic_default_bg).error(errorImg).into((ImageView) view);
                ((ImageView) view).setScaleType(ImageView.ScaleType.FIT_XY);
            }
        });
        binding.bannerWebsite.setAutoPalyTime(2000);
        binding.bannerWebsite.setPointsIsVisible(false);
    }

    private void initTabRecycleView() {
        vsWebsite = binding.vsWebsite.getViewStub();
        vsWebsite.inflate();
        RelativeLayout inflatedWebsite = binding.getRoot().findViewById(R.id.inflatedWebSite);
        tabFirstRecyclerView = inflatedWebsite.findViewById(R.id.tab_first_recyclerView);
        viewPager = inflatedWebsite.findViewById(R.id.viewpager);
        linLl = inflatedWebsite.findViewById(R.id.lin_ll);
        ivCommonView = inflatedWebsite.findViewById(R.id.iv_common_view);
        ivMore = inflatedWebsite.findViewById(R.id.iv_more);
        llMore = inflatedWebsite.findViewById(R.id.ll_more);
        llMore.setOnClickListener(this);
        grayLayout = inflatedWebsite.findViewById(R.id.gray_layout);
        linView = inflatedWebsite.findViewById(R.id.lin_view);
        mBottomSpace = inflatedWebsite.findViewById(R.id.bottom_space);
        mEmptyView = inflatedWebsite.findViewById(R.id.empty_view);
        horizontalScrollView = inflatedWebsite.findViewById(R.id.hzv_scrollview);
        if (entity != null) {
            mBottomSpace.setVisibility(View.VISIBLE);
        }

//        if (websiteType != WEBSITE_FOR_COMPANY){
//            initTabLayout(null, null);
//        }
        tabFirstRecyclerView.setAdapter(mTabAdapter);
        mTabAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mTabAdapter.getItem(position) == null) return;
                PickSelectEntity item = mTabAdapter.getItem(position);
                if (item.isCheck()) return;
                List<PickSelectEntity> data = mTabAdapter.getData();
                if (data != null && !data.isEmpty()) {
                    for (int i = 0; i < data.size(); i++) {
                        if (i == position) {
                            data.get(i).setCheck(true);
                            viewPager.setCurrentItem(position);
                        } else {
                            data.get(i).setCheck(false);
                        }
                    }
                }
                mTabAdapter.notifyDataSetChanged();
            }
        });
    }

    private void initBottomSheetBehavior() {
        bottomSheetBehavior = BottomSheetBehavior.from(binding.contentLayout);
        bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                switch (newState) {
                    case BottomSheetBehavior.STATE_COLLAPSED:
                        //折叠状态
                        Log.i("BottomSheetBehavior", "折叠状态");
                        binding.ivTip.setImageResource(R.drawable.icon_upward);
                        break;

                    case BottomSheetBehavior.STATE_DRAGGING:
                        break;
                    case BottomSheetBehavior.STATE_EXPANDED:
                        binding.ivTip.setImageResource(R.drawable.icon_downward);
                        break;
                    case BottomSheetBehavior.STATE_HIDDEN:
                        //隐藏状态
                        Log.i("BottomSheetBehavior", "隐藏状态");
                    case BottomSheetBehavior.STATE_SETTLING:
                        Log.i("BottomSheetBehavior", "脱离手指自由滑动状态");
                        break;
                    default:
                        throw new IllegalStateException("Unexpected value: " + newState);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                binding.bgLayout.setVisibility(slideOffset == 0f ? View.GONE : View.VISIBLE);
                binding.bgLayout.setAlpha(Math.abs(slideOffset));
            }
        });

    }


    private void initBottomRecyclerView() {
        mBottomAdapter = new BottomAdapter(new ArrayList<>());
        binding.bottomRecyclerView.setLayoutManager(new GridLayoutManager(this, 5));
        binding.bottomRecyclerView.setAdapter(mBottomAdapter);
        mBottomAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mBottomAdapter.getItem(position) == null) return;
                adapterItemClick(mBottomAdapter.getItem(position), position);
            }
        });
    }

    private void adapterItemClick(PermissionMenuEntity.ListEntity entity, int position) {
        if (isMyself && !isEnableClick && websiteType == WEBSITE_FOR_COMPANY) return;
        if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            showDialog();
            return;
        }
        if (!TextUtils.isEmpty(entity.getName())) {
            switch (entity.getName()) {
                case "7_dingdan":
                    if (isMyself) {
                        if (websiteType == WEBSITE_FOR_COMPANY) {
                            AgentTotalOrderActivity.Companion.launch(this, mMenus);
                        }
                        if (websiteType == WEBSITE_FOR_PERSONAL) {
                            if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                                ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_AUTH_NO_AC, this);
                                return;
                            }
                            PersonOrderActivity.Companion.launch(this);
                        }
                    }
                    break;
                case "18_jiameng":
                    viewModel.getInviteList();
                    showChooseType();
                    break;
                case "19_guanzhu":
                    attention();
                    break;
                case "20_jiaoliu":
                    if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                        showDialog();
                    } else {
                        viewModel.getImAccount(websiteNo, websiteType + "");
                    }
                    break;
                case "24_tiaojia":  //会员调价
                    if (!isMyself) {
                        if (mMemberEntity != null && entity != null) {
                            MemberBean memberBean = new MemberBean();
                            memberBean.setMemberUpdateLeverType("2"); //1供方会员 2需方会员
                            memberBean.setCompanyNo(websiteNo);
                            MemberPriceActivity.start(this, memberBean);
                        }
                    }
                    break;
                case "25_chajia":  //会员查价
                    if (!isMyself) {
                        if (mMemberEntity != null && entity != null) {
                            MemberBean memberBean = new MemberBean();
                            memberBean.setMemberUpdateLeverType("1"); //1供方会员 2需方会员
                            memberBean.setCompanyNo(websiteNo);
                            MemberPriceActivity.start(this, memberBean);
                        }
                    }
                    break;
                case "21_tiaoji":  //会员调级
                    if (!isMyself) {
                        if (mMemberEntity != null && this.entity != null) {
                            MemberBean bean = new MemberBean();
                            bean.setCompanyNo(this.entity.getCompanyNo());
                            bean.setCompanyName(this.entity.getName());
                            bean.setCheckType(2); // 1 个人 2 企业
                            if (mMemberEntity.getDemand()) {
                                bean.setNo(mMemberEntity.getDeemandNo());
                                bean.setMemberUpdateLeverType("2"); //2需方会员
                                bean.setLevel(mMemberEntity.getDemandLevel());
                            } else if (mMemberEntity.getSupply()) {
                                bean.setNo(mMemberEntity.getSupplyNo());
                                bean.setMemberUpdateLeverType("1"); //1供方会员
                                bean.setLevel(mMemberEntity.getSupplyLevel());
                            }
                            MemberTransferActivity.start(this, bean, 0);
                        }
                    }
                    break;
                case "23_jiechu":  //会员解除
                    if (!isMyself) {
                        if (mMemberEntity != null && this.entity != null) {
                            MemberBean bean = new MemberBean();
                            bean.setCheckType(2);//企业
                            bean.setCompanyName(this.entity.getName());
                            bean.setCompanyNo(this.entity.getCompanyNo());
                            if (mMemberEntity.getDemand()) {
                                bean.setNo(mMemberEntity.getDeemandNo());
                                bean.setMemberUpdateLeverType("2"); //2需方会员
                                bean.setLevel(mMemberEntity.getDemandLevel());
                            } else if (mMemberEntity.getSupply()) {
                                bean.setNo(mMemberEntity.getSupplyNo());
                                bean.setMemberUpdateLeverType("1"); //1供方会员
                                bean.setLevel(mMemberEntity.getSupplyLevel());
                            }
                            viewModel.getProcessStatus(this, 0, "", bean);
                        }
                    }
                    break;
                case "5_hanxun":
                    if (!isMyself) {
                        postInquiry();
                    } else {
                        if (websiteType == WEBSITE_FOR_PERSONAL) {
                            if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                                ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_AUTH_NO_AC, this);
                                return;
                            }
                        }
                        WebSiteInquiryActivity.Companion.start(this);
                    }
                    break;
                case "13_jicai":
                    if (websiteType == WEBSITE_FOR_COMPANY) {
                        mReallyAgentCentralizedMiningMenus.clear();
                        mReallyAgentCentralizedMiningMenus.addAll(mAgentCentralizedMiningMenus);
                        AgentCentralizedMiningActivity.Companion.launch(this, mReallyAgentCentralizedMiningMenus);
                    }
                    break;
                case "11_shenqing":
                    if (websiteType == WEBSITE_FOR_COMPANY) {
                        if (isMyself) {
                            AgentApplyActivity.Companion.launch(this, mApplyMenus);
                        } else {
                            applyJoin();
                        }
                        break;
                    }
                case "8_fukuan":
                    if (websiteType == WEBSITE_FOR_COMPANY) {
                        if (goToPayEnable) {
                            BusinessManagementActivity.start(this, 1);
                        } else {
                            MToast.showToast(this, "暂无权限，请联系管理员分配");
                        }
                        break;
                    }
                case "10_xunjia":
                    if (isMyself) {
                        if (websiteType == WEBSITE_FOR_TEAM || websiteType == WEBSITE_FOR_COMPANY) {
                            AgentEnquiryActivity.Companion.launch(this, websiteType, permissionEnquiryShop);
                        } else if (websiteType == WEBSITE_FOR_PERSONAL) {
                            if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                                ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_AUTH_NO_AC, this);
                                return;
                            }
                            AgentEnquiryActivity.Companion.launch(this, websiteType, permissionEnquiryShop);
                        }

                    } else {
                        viewModel.getEnquiryList();
                        showChooseType();
                    }
                    break;
                case "16_hetong":
                    if (isMyself) {
                        if (websiteType == WEBSITE_FOR_COMPANY) {
                            viewModel.getCompanyDetail(this);
                        }
                    }
                    break;
                case "27_baojia": //报价
                    WebsiteOfferListActivity.Companion.launch(this, websiteNo);
                    break;
                case "26_heyue": //合约
                    WebsiteContractListActivity.Companion.launch(this, websiteNo);
                    break;
                default:
                    MenuClickUtils.getInstance().handlerWebsiteMenu(this, websiteType, isMyself, entity);
            }
        }
    }

    //关注
    private void attention() {
        if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            showDialog();
        } else {
            viewModel.attentionCompanyStatus(websiteNo, websiteType);
        }
    }

    //发起函询
    private void postInquiry() {
        if (entity == null) {
            return;
        }
        if (websiteType == WEBSITE_FOR_PERSONAL) {
            WebSitePostInquiryActivity.Companion.start(WebsiteInfoActivity.this, entity.getRealName(), websiteNo, websiteType);
        } else if (websiteType == WEBSITE_FOR_COMPANY) {
            WebSitePostInquiryActivity.Companion.start(WebsiteInfoActivity.this, entity.getName(), websiteNo, websiteType);
        } else if (websiteType == WEBSITE_FOR_TEAM) {
            WebSitePostInquiryActivity.Companion.start(WebsiteInfoActivity.this, entity.getName(), websiteNo, websiteType, entity.getUserNo());
        } else if (websiteType == WEBSITE_FOR_ORGANIZE) {
            WebSitePostInquiryActivity.Companion.start(WebsiteInfoActivity.this, entity.getOrganizationName(), websiteNo, websiteType, entity.getUserNo());
        }
    }

    //申请加盟
    private void applyJoin() {
        if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            showDialog();
        } else {
            if (entity == null) return;
            //int mType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
            if (websiteType == WEBSITE_FOR_COMPANY) {
                if (UserPermissionUtils.getInstance().getMemberPermission(viewModel.list, "twoLevel_huiyuanguanli", "14_shenqingguanli")) {//申请加盟
                    QualityMemberBean bean = new QualityMemberBean();
                    bean.setCompanyNo(websiteNo);
                    bean.setCompanyName(entity.getName());
                    MemberApplyJoinActivity.start(WebsiteInfoActivity.this, bean);
                } else {
                    MToast.showToast(WebsiteInfoActivity.this, "您当前为个人/团队身份，暂不支持该操作");
                }
            } else {
                MToast.showToast(WebsiteInfoActivity.this, "个人/团队网站暂不支持该操作");
            }
        }
    }

    //邀请加盟
    private void inviteJoin() {
        if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            showDialog();
        } else {
            if (entity == null) {
                return;
            }
            if (!MemberConfig.getInstance().isHavePermission("14_yaoqinghuiyuan1")) {
                MToast.showToast(getActivity(), "没有权限操作，请找企业管理员分配权限");
                return;
            }

            //int mType1 = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
            if (websiteType == WEBSITE_FOR_COMPANY) {
                //if (UserPermissionUtils.getInstance().getMemberPermission(viewModel.list, "twoLevel_huiyuanguanli", "14_yaoqingguanli")) {//邀请加盟
                QualityMemberBean bean1 = new QualityMemberBean();
                bean1.setCompanyNo(websiteNo);
                bean1.setCompanyName(entity.getName());
                bean1.setServiceTypeName(entity.getServiceTypeName());
                bean1.setServiceType(entity.getServiceType());
                MemberInviteJoinActivity.start(WebsiteInfoActivity.this, bean1);
//                } else {
//                    MToast.showToast(WebsiteInfoActivity.this, "此功能无权限，请联系管理员分配权限!");
//                }
            } else {
                MToast.showToast(WebsiteInfoActivity.this, "个人/团队网站暂不支持该操作");
            }
        }
    }

    private View getMemberView() {
        mMemberHeaderView = LayoutInflater.from(this).inflate(R.layout.item_header_website_self_support, binding.recyclerViewTag, false);
        mMemberTv = mMemberHeaderView.findViewById(R.id.tv_content);
        return mMemberHeaderView;
    }

    //信用评分
    private View getScoreView() {
        mScoreView = LayoutInflater.from(this).inflate(R.layout.item_header_website_self_support, binding.recyclerViewEmpty, false);
        tvScore = mScoreView.findViewById(R.id.tv_content);
        mScoreView.setVisibility(View.GONE);
        return mScoreView;
    }

    private View getSelfSupportView() {
        mSelfSupportHeaderView = LayoutInflater.from(this).inflate(R.layout.item_header_website_self_support, binding.recyclerViewTag, false);
        ((TextView) mSelfSupportHeaderView.findViewById(R.id.tv_content)).setText("自营");
        mSelfSupportHeaderView.setVisibility(View.GONE);
        return mSelfSupportHeaderView;
    }

    @Override
    protected void init() {
        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            if (websiteType != WEBSITE_FOR_TEAM) {
                //setBottomShow();
                //viewModel.isBelongCurrentCompany(websiteNo, websiteType);改为本地判断是不是自己或者当前企业
            }
            setBottomShow();
        } else {
            //binding.linTool.setVisibility(View.VISIBLE);
        }
        switch (websiteType) {
            case WEBSITE_FOR_COMPANY:
            case WEBSITE_FOR_TEAM:
                binding.llQiyi.setVisibility(View.VISIBLE);
                break;
            case WEBSITE_FOR_PERSONAL:
                binding.llMy.setVisibility(View.VISIBLE);
                break;
        }
        //viewModel.getAttentionCompanyStatus(shopId);
        //websiteNo = "1377559862367621120";
        if (websiteType == WEBSITE_FOR_COMPANY) {
            viewModel.getWebsiteConfigure(websiteNo, websiteType);
        } else {
            viewModel.getWebsiteInfo(websiteNo, websiteType);
            viewModel.getJudgeFirstMenuData(websiteNo, websiteType);
            binding.websiteHeadView.loadTemplate(WebsiteHeadView.TEMPLATE_TYPE_ONE, websiteType);
        }
        //if (isMyself) {
        //viewModel.getBottomPermission(websiteNo, websiteType);
        //}
    }

    private void setBottomShow() {
        if (websiteType == WEBSITE_FOR_PERSONAL) {
            isMyself = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "")
                    .equals(websiteNo);
        } else if (websiteType == WEBSITE_FOR_COMPANY) {
            isMyself = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
                    .equals(websiteNo);
        } else {
            isMyself = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
                    .equals(websiteNo);
        }
    }

    private void initTabLayout
            (List<WebsiteConfigureEntity.NavigateBarEntity> navigateBars, List<Integer> filterMenus) {
        ArrayList<Fragment> mFragments = new ArrayList<>();
        List<String> tabNames = viewModel.getTabName(websiteType, navigateBars, filterMenus, isMyself);
        mTabAdapter.setNewData(viewModel.getPopupList(tabNames));
        if (tabNames == null || tabNames.isEmpty()) {
            tabFirstRecyclerView.setPadding(0, 0, 0, 0);
            return;
        }
        //int colums = 0;
        //if (viewModel.getPopupList(tabNames).size() % 2 != 0){
        //colums = viewModel.getPopupList(tabNames).size() / 2 + 1;
        //} else {
        //colums = viewModel.getPopupList(tabNames).size() / 2;
        //}
        //ViewGroup.LayoutParams layoutParams = tabFirstRecyclerView.getLayoutParams();
        if (mConfigureEntity != null) {
//            if (mConfigureEntity.getUseTemplate() != 2) {
//                tabFirstRecyclerView.setLayoutManager(new GridLayoutManager(WebsiteInfoActivity.this, 5));
//                mTabAdapter.setTextSizeIsBig(true);
//                llMore.setVisibility(View.GONE);
//            } else {
            if (viewModel.getPopupList(tabNames).size() < 5) {
                tabFirstRecyclerView.setLayoutManager(new GridLayoutManager(WebsiteInfoActivity.this, 5));
            } else {
                tabFirstRecyclerView.setLayoutManager(new GridLayoutManager(WebsiteInfoActivity.this, viewModel.getPopupList(tabNames).size()));
            }
            llMore.setVisibility(mTabAdapter.getData().isEmpty() ? View.GONE : View.VISIBLE);
            mTabAdapter.setTextSizeIsBig(true);
//            }
            //layoutParams.width = ((SizeUtils.getScreenWidth(this) - SizeUtils.dp2px(56)) / 5) * colums;
            //} else {
            //layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        } else {
            tabFirstRecyclerView.setLayoutManager(new GridLayoutManager(WebsiteInfoActivity.this, 5));
        }
        //tabFirstRecyclerView.setLayoutParams(layoutParams);
        tabFirstRecyclerView.setPadding(SizeUtils.dp2px(8), SizeUtils.dp2px(10), SizeUtils.dp2px(8), 0);
        for (int i = 0; i < tabNames.size(); i++) {
            switchFragmentView(mFragments, tabNames.get(i));
        }
        SlidingFragmentPagerAdapter mAdapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, tabNames.toArray(new String[]{}));
        viewPager.setAdapter(mAdapter);
        viewPager.setOffscreenPageLimit(tabNames.size());
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position < mTabAdapter.getData().size()) {
                    for (int i = 0; i < mTabAdapter.getData().size(); i++) {
                        if (i == position) {
                            mTabAdapter.getData().get(i).setCheck(true);
                            viewPager.setCurrentItem(position);
                            currentPosition = position;
                        } else {
                            mTabAdapter.getData().get(i).setCheck(false);
                        }
                    }
                    mTabAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //binding.tabLayout.setupWithViewPager(binding.viewpager);
//        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
//            @Override
//            public void onTabSelected(TabLayout.Tab tab) {
//                currentPosition = tab.getPosition();
//            }
//
//            @Override
//            public void onTabUnselected(TabLayout.Tab tab) {
//
//            }
//
//            @Override
//            public void onTabReselected(TabLayout.Tab tab) {
//
//            }
//        });
        viewPager.setCurrentItem(currentPosition);
        linLl.setVisibility(View.VISIBLE);
        mEmptyView.setVisibility(mTabAdapter.getData().isEmpty() ? View.VISIBLE : View.GONE);
    }


    /**
     * 根据tabName来动态加载对应功能模块
     *
     * @param mFragments
     * @param tabName
     */
    private void switchFragmentView(ArrayList<Fragment> mFragments, String tabName) {
        switch (tabName) {
            case "经营业务":
                mFragments.add(OperatingBusinessForWebsite.newInstance(websiteNo, websiteType, childPosition, isMyself));
                break;
            case "需求公告":
                mFragments.add(DemandAnnouncementForWebsite.newInstance(websiteNo, websiteType, isMyself));
                break;
            case "会员经营":
                mFragments.add(OtherInquiryFragment.Companion.newInstance());
                break;
            case "经营业绩":
                mFragments.add(OperatingResultsForWebsite.newInstance(websiteNo, websiteType));
                break;
            case "专项资质":
                mFragments.add(SpecialQualificationForWebsite.newInstance(websiteNo, websiteType));
                break;
            case "专项资产":
                mFragments.add(SpecialAssetsForWebsite.newInstance(websiteNo, websiteType));
                break;
            case "经营动态":
                mFragments.add(BusinessDynamicsForWebsite.newInstance(websiteNo, websiteType));
                break;
            case "荣誉荣耀":
                mFragments.add(HonorGloryForWebsite.newInstance(websiteNo, websiteType));
                break;
            case "知识产权":
                mFragments.add(IntellectualPropertyForWebsite.newInstance(websiteNo, websiteType, isMyself));
                break;
            case "宣传展示":
                mFragments.add(PromotionalAlbumForWebsite.newInstance(websiteNo, websiteType));
                break;
            case "简介":
            case "企业简介":
            case "个人简介":
            case "团队简介":
            case "政府简介":
                mFragments.add(IntroductionForWebsite.newInstance(websiteNo, websiteType));
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.right_image_view:
                addPopWindow.showPopwindow(binding.include.rightImageView, true);
                break;
            case R.id.lin_attention:
            case R.id.tv_attention:
                attention();
                break;
            case R.id.lin_im:
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    showDialog();
                } else {
                    MToast.showToast(WebsiteInfoActivity.this, "服务升级中");
                }
                break;
            case R.id.iv_address_lat:
            case R.id.iv_address_lat_person:
                openMap(entity);
                break;
            case R.id.lin_join:
                applyJoin();
                break;
            case R.id.lin_invite:
                inviteJoin();
                break;
            case R.id.lin_ll:
            case R.id.ll_more:
                requestManager.load(R.drawable.icon_more_up).into(ivMore);
                showPopWindow();
                break;
            case R.id.lin_inquiry:
                postInquiry();
                break;
            case R.id.tv_VR:
                if (!ClickUtils.isDoubleClick()) {
                    if (entity != null && !TextUtils.isEmpty(entity.getVrUrl())) {
                        WebViewX5HostActivity.start(this, entity.getVrUrl());
                    }
                }
                break;
            case R.id.tv_announcement_more:
                if (!ClickUtils.isDoubleClick()) {
                    WebsiteAnnouncementListActivity.Companion.launch(this, websiteNo, websiteType + "");
                }
                break;
        }
    }


    //地图
    private void openMap(WebsiteInfoEntity entity) {
        Double lat = 0.0, lng = 0.0;
        if (entity == null) {
            return;
        }
        if (!TextUtils.isEmpty(entity.getLatitude())) {
            lat = Double.valueOf(entity.getLatitude());
        }
        if (!TextUtils.isEmpty(entity.getLongitude())) {
            lng = Double.valueOf(entity.getLongitude());
        }
        String address = "";
        String name = "";
        if (websiteType == 1) {//企业
            address = entity.getMapAddress();
            name = entity.getName();
        } else if (websiteType == 0) {//个人
            address = entity.getDetailAddress();
            name = entity.getRealName();
        } else if (websiteType == 2) {//团队
            address = entity.getBusinessAddress();
            name = entity.getName();
        } else if (websiteType == 3) {//组织
            address = entity.getAddress();
            name = entity.getOrganizationName();
        }
        GetPositionActivity.start(getActivity(), lng, lat, address, name);
    }

    //未登录弹框跳转认证
    public void showDialog() {
        View view = View.inflate(this, R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("温馨提示");
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("确定");
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("未登录，请先登录。");

        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_MAIN_ACTIVITY_JUMP);
                roundCornerDialog.dismiss();
            }
        });

        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    private Boolean getPermission(String title) {
        if (viewModel.list != null)
            for (PermissionMenuEntity entity : viewModel.list) {
                if ("oneLevel_huiyuanjingying".equals(entity.getName())) {//会员经营
                    for (PermissionMenuEntity.ListEntity entity1 : entity.getList()) {
                        if (TextUtils.equals(entity1.getName(), "twoLevel_huiyuanguanli")) {//会员管理
                            if (entity1.getList() != null && !entity1.getList().isEmpty()) {
                                for (PermissionMenuEntity.ListEntity entity2 : entity1.getList()) {
                                    if (entity2.getName().equals(title)) {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        return false;
    }

    /*
     * 返回企业信息并实现展示
     * */
    public void showWebsiteInfo(WebsiteInfoEntity entity) {
        viewModel.getAnnouncementList(websiteNo, websiteType + ""); //获取公告列表
        if (entity == null) {
            return;
        }
        //获取公司信息成功在加载其他接口
        if (websiteType == WEBSITE_FOR_COMPANY || websiteType == WEBSITE_FOR_PERSONAL) {
            viewModel.getPermissionMenu(websiteType);
        }
        binding.contentLayout.setVisibility(View.VISIBLE);
        if (mBottomSpace != null) {
            mBottomSpace.setVisibility(View.VISIBLE);
        }
        if (websiteType != WEBSITE_FOR_COMPANY) {
            viewModel.getWebsiteBanner(websiteNo, websiteType);//获取网站广告列表
        }
        if (isMyself) {
            if (websiteType == WEBSITE_FOR_COMPANY) {
                viewModel.getCompanyBottomMenus(websiteType, isMyself, null, mConfigureEntity);
            } else {
                viewModel.getBottomMenu(websiteType, isMyself, null);
            }
            binding.websiteHeadView.renderView(entity, requestManager, null);
        } else {
            if (WebsiteInfoActivity.WEBSITE_FOR_COMPANY == websiteType || WebsiteInfoActivity.WEBSITE_FOR_PERSONAL == websiteType
                    && (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 1) ||
                    SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 0) {//企业或者个人才会有会员关系
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    binding.ivTip.setVisibility(View.VISIBLE);
                    viewModel.getBottomMenu(websiteType, isMyself, null);
                    binding.websiteHeadView.renderView(entity, requestManager, null);
                } else {
                    binding.ivTip.setVisibility(View.GONE);
                    viewModel.getWebsiteMember(websiteNo);
                }
            } else if (WebsiteInfoActivity.WEBSITE_FOR_COMPANY == websiteType || WebsiteInfoActivity.WEBSITE_FOR_PERSONAL == websiteType) {
                binding.ivTip.setVisibility(View.VISIBLE);
                viewModel.getCompanyBottomMenus(websiteType, isMyself, null, mConfigureEntity);
                binding.websiteHeadView.renderView(entity, requestManager, null);
            } else {
                binding.ivTip.setVisibility(View.VISIBLE);
                viewModel.getBottomMenu(websiteType, isMyself, null);
                binding.websiteHeadView.renderView(entity, requestManager, null);
            }
        }
        if (websiteType == WEBSITE_FOR_ORGANIZE) {
            binding.include.titleView.setText(entity.getOrganizationName());
        } else {
            binding.include.titleView.setText(TextUtils.isEmpty(entity.getName()) ? entity.getRealName() : entity.getName());
        }
        if (websiteType == WEBSITE_FOR_TEAM) {
            if (TextUtils.isEmpty(entity.getMapAddress())) {
                entity.setMapAddress(entity.getBusinessAddress());
            }
            if (TextUtils.isEmpty(entity.getServiceTypeName())) {
                entity.setServiceTypeName(entity.getBusinessType());
            }
            //判断是否属于当前团队
            //viewModel.isBelongCurrentGroup(entity.getNo());
        }
        viewModel.entityMutableLiveData.setValue(entity);
        binding.setViewModel(viewModel);
        this.entity = entity;
        if (websiteType == WEBSITE_FOR_COMPANY) {
            if (TextUtils.isEmpty(entity.getMapAddress())) {
                binding.ivAddressLat.setVisibility(View.GONE);
            } else {
                binding.ivAddressLat.setVisibility(View.VISIBLE);
            }
        } else if (websiteType == WEBSITE_FOR_PERSONAL) {
            if (TextUtils.isEmpty(entity.getDetailAddress())) {
                binding.ivAddressLat.setVisibility(View.GONE);
            } else {
                binding.ivAddressLat.setVisibility(View.VISIBLE);
            }
        } else {
            if (TextUtils.isEmpty(entity.getBusinessAddress())) {
                binding.ivAddressLat.setVisibility(View.GONE);
            } else {
                binding.ivAddressLat.setVisibility(View.VISIBLE);
            }
        }
        int RIcon = R.mipmap.image_website_dfg;
        if (websiteType == WEBSITE_FOR_COMPANY) {
            RIcon = R.mipmap.image_website_dfg;
        } else if (websiteType == WEBSITE_FOR_PERSONAL) {
            RIcon = R.mipmap.def_photo;
        } else if (websiteType == WEBSITE_FOR_TEAM) {
            RIcon = R.drawable.icon_team_default;
        } else if (websiteType == WEBSITE_FOR_ORGANIZE) {
            RIcon = R.drawable.icon_organization_default;
        }
        RequestOptions options = new RequestOptions()
                .placeholder(RIcon)//图片加载出来前，显示的图片
                .error(RIcon)//图片加载失败后，显示的图片
                .transform(new CircleCrop());
        requestManager.load(entity.getLogo()).apply(options).into(binding.ivShopAvatar);

        if (mSelfSupportHeaderView != null) {
            mSelfSupportHeaderView.setVisibility(websiteType == WEBSITE_FOR_COMPANY && entity.isSelfSupport() ? View.VISIBLE : View.GONE);
        }
        //mMemberTv.setText("三星会员");

        if (!TextUtils.isEmpty(entity.getServiceTypeName())) {
            List<String> serviceNameList = new ArrayList<>();
            serviceNameList.addAll(entity.getServiceTypeList(1));
            //mAdapter.setData(serviceNameList);
        }
        binding.tvAttention.setVisibility(isMyself ? View.INVISIBLE : View.VISIBLE);
        binding.tvVR.setVisibility(TextUtils.isEmpty(entity.getVrUrl()) ? View.GONE : View.VISIBLE);
        if (mScoreView != null) {
            mScoreView.setVisibility(TextUtils.isEmpty(entity.getReallyScore()) ? View.GONE : View.VISIBLE);
        }
        if (tvScore != null) {
            tvScore.setText(getResources().getString(R.string.website_score, entity.getReallyScore()));
        }
    }

    /*
     * 设置关注企业网站状态
     * */
    private int mAttentionPosition = -1; //关注的位置

    public void setAttentionCompanyStatus(@NotNull Boolean flag) {
//        if (flag) {
//            binding.ivAttentionBottom.setImageResource(R.drawable.icon_attention_nomal_red);
//            binding.tvAttentionBottom.setText("已关注");
//            binding.tvAttentionBottom.setTextColor(ContextCompat.getColor(WebsiteInfoActivity.this, R.color.color_main));
//        } else {
//            binding.ivAttentionBottom.setImageResource(R.mipmap.attention_unnomal);
//            binding.tvAttentionBottom.setText("关注");
//            binding.tvAttentionBottom.setTextColor(ContextCompat.getColor(WebsiteInfoActivity.this, R.color.color_tab_two));
//        }
        if (!flag) {
            //MToast.showToast(this, "取消关注成功");
            binding.tvAttention.setText("关注");
            binding.tvAttention.setTextColor(getResources().getColor(R.color.color_main));
            binding.tvAttention.setBackgroundResource(R.drawable.shape_rd5_str1_red_bg);
        } else {
            //MToast.showToast(this, "关注成功");
            binding.tvAttention.setText("已关注");
            binding.tvAttention.setTextColor(getResources().getColor(R.color.color_tab_three));
            binding.tvAttention.setBackgroundResource(R.drawable.shpae_rd5_str1_grey_bg);
        }
        binding.websiteHeadView.setAttention(flag, isMyself);
        if (!isMyself) {
            List<PermissionMenuEntity.ListEntity> data = mBottomAdapter.getData();
            if (data != null && !data.isEmpty()) {
                for (PermissionMenuEntity.ListEntity entity : data) {
                    if (entity.getName().equals("19_guanzhu")) {
                        mAttentionPosition = data.indexOf(entity);
                        entity.setIcon(flag ? "yiguanzhu_red" : "guanzhu_grey");
                        entity.setTitle(flag ? "已关注" : "关注");
                    }
                }
                if (mAttentionPosition != -1) {
                    mBottomAdapter.notifyItemChanged(mAttentionPosition);
                    mAttentionPosition = -1;
                }
            }
        }
    }

    /*
     * 设置底部Tab栏是否显示
     * */
    public void showBottomTab(boolean flag) {
        if (!flag) {
            //binding.linTool.setVisibility(View.VISIBLE);
        }
    }

    /*
     * 是否关注该企业
     * */
    public void isShowAttention(Boolean flag) {
        setAttentionCompanyStatus(flag);
    }

    /*
     * 返回关注该企业结果
     * */
    public void attentionShow(Boolean flag) {
        if (flag)
            viewModel.getUserFocusCompanyStatus(websiteNo, websiteType);
    }

    /*
     * 多Tab展示PopWindow界面
     * */
    private void showPopWindow() {
        if (mPopup == null) {
            mPopup = new PickHallBidingPopWindow(this);
            mPopup.setBgView(grayLayout);
            mPopup.setOnResultClick(new BasePopWindow.OnResultClick() {
                @Override
                public void result(Object key1, Object key2, Object key3) {
                    int position = (int) key3;
                    currentPosition = position;
                    tabFirstRecyclerView.scrollToPosition(position);
                    horizontalScrollView.scrollTo(SizeUtils.dp2px(60) * currentPosition, 0);
                    viewPager.setCurrentItem(position);
                }
            });
            mPopup.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
                @Override
                public void disMiss() {
                    requestManager.load(R.drawable.icon_more_down).into(ivMore);
                }
            });
            mPopup.setData(viewModel.getPopupList(viewModel.getTabName(websiteType, mConfigureEntity == null ? null : mConfigureEntity.getNavigateBar(), mFilterMenus, isMyself)));
        }
        mPopup.showPopwindow0(linView);
        mPopup.setDefItem(currentPosition);
    }


    /**
     * event 如果token h5失效 然后登录成功 刷新网站
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_WEBSITEINFO) {
            if (isMyself) {
                websiteNo = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, websiteNo);
                websiteType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, websiteType);
                init();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isEnableClick = false;
        EventBus.getDefault().unregister(this);
    }

    public void renderBottomView(List<PermissionMenuEntity.ListEntity> list) {
        if (list == null) {
            return;
        }
        totalMenu.clear();
        totalMenu.addAll(list);
        binding.ivTip.setVisibility(list.size() > 5 ? View.VISIBLE : View.GONE);
        setBottomData(list);
        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PC_TOKEN, ""))) {
            viewModel.getUserFocusCompanyStatus(websiteNo, websiteType);
        } else {
            setAttentionCompanyStatus(false);
        }
    }

    private void setBottomData(List<PermissionMenuEntity.ListEntity> list) {
        if (list == null) return;
        mBottomAdapter.setNewData(list);
    }

    //底部操作栏---询价、邀请
    private void showChooseType() {
        ChooseTypeFragment fragment = (ChooseTypeFragment) getSupportFragmentManager().findFragmentByTag(ChooseTypeFragment.TAG);
        if (fragment != null) {  //连续点了两次Click。已经添加过了
            return;
        }
        fragment = ChooseTypeFragment.Companion.newInstance(viewModel.mList);
        fragment.show(getSupportFragmentManager(), ChooseTypeFragment.TAG);
    }


    private void checkPermission() {
        if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            showDialog();
            return;
        }
        if (PermissionsUtil.hasPermission(getActivity(), Manifest.permission.CAMERA)) {
            ScanActivity.start(getActivity());
        } else {
            PermissionsUtil.requestPermission(this, new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    ScanActivity.start(getActivity());
                }

                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    MToast.showLongToast(getActivity(), "请先获取相机权限");
                }
            }, Manifest.permission.CAMERA);
        }
    }

    // 解除会员回调
    public void removeMember() {
        viewModel.getWebsiteMember(websiteNo);
    }

    //点击询价、邀请 时间处理
    @Override
    public void clickItem(@NotNull PickFilterEntity<Object> entity) {
        switch (entity.getName()) {
            case "商品询价":   //商品发布询价
                Intent createGood = new Intent(this, NewPurchasesActivity.class);
                createGood.putExtra("GOOD_EDIT", false);
                createGood.putExtra("GOOD_ADD", false);
                createGood.putExtra("GOOD_ENTITY", new GoodsItemEntity());
                startActivity(createGood);
                break;
            case "求租询价":
                DefaultEmptyActivity.Companion.launch(this, "求租询价");
                break;
            case "出租询价":
                DefaultEmptyActivity.Companion.launch(this, "出租询价");
                break;
            case "邀请会员":
                inviteJoin();
                break;
            case "邀请投标":
                TenderInviteBiddingActivity.Companion.launch(this, true, websiteNo);
                break;
            case "邀请竞价":
                TenderInviteBiddingActivity.Companion.launch(this, false, websiteNo);
                break;
            case "邀请报价":
                DefaultEmptyActivity.Companion.launch(this, "邀请报价");
                break;
            case "邀请集采":
                DefaultEmptyActivity.Companion.launch(this, "邀请集采");
                break;
            default:
                break;
        }
    }


    class BottomAdapter extends BaseQuickAdapter<PermissionMenuEntity.ListEntity, BaseViewHolder> {

        //图标
        private ImageView iv_icon;
        //本地图片地址ID
        private int resID;

        // 绑定数据和参数
        public BottomAdapter(List<PermissionMenuEntity.ListEntity> datas) {
            super(R.layout.item_website_bottom, datas);
        }

        @Override
        protected void convert(BaseViewHolder holder, PermissionMenuEntity.ListEntity entity) {
            //DataBinding绑定布局，实现数据传递
            ItemWebsiteBottomBinding binding = DataBindingUtil.bind(holder.itemView);
            binding.setViewModel(entity);
            //图标
            iv_icon = holder.itemView.findViewById(R.id.iv_icon);
            //获取entity的图标信息
            String icon = entity.getIcon();
            //判断是否存在
            if (!TextUtils.isEmpty(icon)) {
                resID = getResources().getIdentifier(icon, "drawable", getPackageName());
                Log.e("图标名称", icon);
            }
            //判断本地图标地址id是否找到
            if (resID != 0) {
                Glide.with(mContext)
                        .load(resID)
                        .apply(new RequestOptions()
                                .error(R.drawable.user_center_def_img)
                                .placeholder(R.drawable.user_center_def_img)
                                .fallback(R.drawable.user_center_def_img))
                        .into(iv_icon);
            } else {
                Glide.with(mContext).load(R.drawable.user_center_def_img).into(iv_icon);
            }
        }
    }


}

